package com.huiminpay.paymentagent.mq;

import com.alibaba.fastjson.JSON;
import com.huiminpay.paymentagent.api.conf.AliConfigParam;
import com.huiminpay.paymentagent.api.dto.PaymentResponseDTO;
import com.huiminpay.paymentagent.api.dto.TradeStatus;
import com.huiminpay.paymentagent.api.service.IPayAgentService;
import com.huiminpay.transaction.api.dto.OrderResultDTO;
import com.huiminpay.transaction.api.dto.PayChannelParamDTO;
import com.huiminpay.transaction.service.IPayChannelService;
import com.huiminpay.transaction.service.ITransactionService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Slf4j
@Component
@RocketMQMessageListener(topic = PayProducer.TOPIC_ORDER, consumerGroup = "CID_PAYMENT_CONSUMER")
public class PayConsumer implements RocketMQListener<MessageExt> {
    @Reference
    ITransactionService transactionService;
    @Reference
    IPayAgentService payAgentService;
    @Reference
    IPayChannelService payChannelService;
    @Override
    public void onMessage(MessageExt message) {
        byte[] body = message.getBody();
        String jsonStr = new String(body);
        PaymentResponseDTO paymentResponseDTO = JSON.parseObject(jsonStr, PaymentResponseDTO.class);
        String outTradeNo = paymentResponseDTO.getOutTradeNo();

        // 1.查询订单状态
        OrderResultDTO orderResultDTO = transactionService.selectPayOrderByOrderNo(outTradeNo);
        if(orderResultDTO.getTradeState().equals("2")){
            //交易状态支付状态,0-订单生成,1-支付中(目前未使用),2-支付成功,3-业务处理完成
            return;
        }
        // 2.如果订单状态为未支付则查询支付宝状态
        PayChannelParamDTO payChannelParamDTO = payChannelService.queryParamByAppPlatformAndPayChannel(orderResultDTO.getAppId(), orderResultDTO.getChannel(), orderResultDTO.getPayChannel());
        String param = payChannelParamDTO.getParam();
        AliConfigParam aliConfigParam = JSON.parseObject(param, AliConfigParam.class);
        PaymentResponseDTO paymentResponseDTO1 = payAgentService.queryAlipayOrderInfo(aliConfigParam, outTradeNo);


        //3.如果获取到支付宝状态为未支付则消费重试 就是抛个异常
        if(paymentResponseDTO1.getTradeState().equals(TradeStatus.REVOKED)
                ||paymentResponseDTO1.getTradeState().equals(TradeStatus.USERPAYING)){
            int reconsumeTimes = message.getReconsumeTimes();
            if(reconsumeTimes<5){
                new RuntimeException("当前订单未支付，消费重试，次");
            }
            return;
        }

        // 4.如果获取到支付宝状态为已支付 更新订单
        orderResultDTO.setTradeState("2");
        orderResultDTO.setPaySuccessTime(LocalDateTime.now());
        orderResultDTO.setPayChannelTradeNo(paymentResponseDTO1.getTradeNo());
        transactionService.updatePayorder(orderResultDTO);
    }
}
